<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
//include("sqlconnect.php");
//include("sqlgenerator.php");

function store_ticket($ticket_no, $ticket_rate, $coupon_value) {
    //Semaphore properties
    if( !function_exists('sem_get') )
    {
        function sem_get($key) {
            db_connect();

            $query = get_sem($key);
            $result = db_query($query);

            try {
                $row = mysql_fetch_array($result);
                $value = $row['value'];
            } catch (Exception $e) {
                $value = 1;
            }
            return $value;
        }

        function sem_acquire($key) {
            $i=0;
            while(sem_get($key)==1) {
                usleep(20000);
                if($i++>250)
                    return false;
            }

            db_connect();

            $query = update_sem($key,1);
            $result = db_query($query);
            return true;

        }

        function sem_release($key) {
            $query = update_sem($key,0);
            $result = db_query($query);

        }

        $semaphore = 1;
        if(!sem_acquire($semaphore))
            echo "Failed on sem_get().\n";
    } else {
        $key = 960170;
        $max = 1;
        $permissions = 0666;
        $autoRelease = 1;

        //Open a new or get an existing semaphore
        $semaphore = sem_get($key, $max, $permissions, $autoRelease);
        $semaphore = sem_get($key);
        if(!$semaphore) {
            echo "Failed on sem_get().\n";
        }

        sem_acquire($semaphore);
    }
    
    db_connect();

    $query = get_ticketinfo($ticket_rate);
    $result = db_query($query);
    //echo $query;
    $row=mysql_fetch_array($result);
    try {
        $l[0] = (float)$row['l0'];
        $l[1] = (float)$row['l1'];
        $l[2] = (float)$row['l2'];
    } catch (Exception $e) {
        $l[0] = 2.9;
        $l[1] = 0.6;
        $l[2] = 0.5;
    }

    $count_level = 3;

    $query=get_last_ticket();
    $result = db_query($query);
    $row = mysql_fetch_array($result);
    if ($row) {
        try {
            $level = (int)$row['level'];
            $parent_ticket_no = (int)$row['parent_ticket_no'];
        } catch (Exception $e) {
            $level = -10;
            $parent_ticket_no = '';
        }
    } else {
        $level = -10;
        $parent_ticket_no = '';
    }

    $query=get_all_childs($parent_ticket_no);
    $result = db_query($query);
    $num_childs = mysql_num_rows($result);

    // Check if this is the first ticket for the system
    if ($level<0) {
        $parent_ticket_no = 0;
        $level = 0;
    } else {
        $query=get_all_tickets_level(0);
        $result = db_query($query);
        $num_tickets_level_zero = mysql_num_rows($result);

        $max_tickets_curr_level = $num_tickets_level_zero*pow(3,$level);

        $query=get_all_tickets_level($level);
        $result = db_query($query);
        $num_tickets_curr_level = mysql_num_rows($result);

            // Can be inserted in this level
        if($num_tickets_curr_level<$max_tickets_curr_level) {
            // Can be inserted under the same parent
            if ($num_childs<$count_level) {
                // Nothing needs to be done here, it will be taken care
                // at the end of this function
            } else { // Needs to be inserted under the next parent
                $query=get_all_tickets_level($level-1);
                $result = db_query($query);

                $i=0;
                while($row=mysql_fetch_array($result)) {
                    if($row['ticket_no']==$parent_ticket_no) {
                        break;
                    }
                    $i++;
                }

                // Can be inserted in the next parent in the same level
                //if($i<$count[$level-1] && ($row = mysql_fetch_array($result))) {
                if($row = mysql_fetch_array($result)) {
                    $parent_ticket_no = $row['ticket_no'];
                } else { // Should be inserted in the next level
                    $query = get_first_ticket_level($level);
                    $result = db_query($query);
                    $row = mysql_fetch_array($result);
                    $parent_ticket_no = $row['ticket_no'];
                    $level = $level + 1;
                }
            }
        } else { // Needs to be inserted at the next level
            $query = get_first_ticket_level($level);
            $result = db_query($query);
            $row = mysql_fetch_array($result);
            $parent_ticket_no = $row['ticket_no'];
            $level = $level + 1;
        }

        
    }

    $fields[0]=$ticket_no;
    $fields[1]=$coupon_value;
    $fields[2]=0;
    $fields[3]=$parent_ticket_no;
    $fields[4]=$level;

    $query=insert_ticket($fields);
    $result = db_query($query);

    // Find the first three parents to add money
    $i = 0;
    do {
        $parent_ticket[$i] = $parent_ticket_no;
        
        $query = get_ticket($parent_ticket_no);
        $result = db_query($query);
        $row = mysql_fetch_array($result);
        if ($row) {
            $parent_ticket_no = $row['parent_ticket_no'];
            //echo $parent_ticket_no;
        } else {
            break;
        }
        $parent_ticket[++$i] = $parent_ticket_no;
    } while ($parent_ticket_no);

    $redraw = false;
    // The last one will be null as the parent of the level 0 ticket will be null
    $parent_count = count($parent_ticket) - 1;

    $j = 1;
    for ($i=$parent_count-$count_level;$i<$parent_count;$i++) {
        // Update only valid parents
        if($i<0) {
            continue;
        }
        $parent = $parent_ticket[$i];
        $query = get_ticket($parent);
        $result = db_query($query);
        $row = mysql_fetch_array($result);

        $value = $row['value'] + $l[$count_level-$j];

        if($row['level']==0 && $row['max_coupon_value']<=$value) {
            $value=$row['max_coupon_value'];
            $ticket_no=$row['ticket_no'];
            $update_level = -1;
            $query = update_ticket_level_and_value($ticket_no,$update_level,$value);
            $result = db_query($query);
            //echo $query;
            // Redraw the tree by decrementing the levels of all the tickets
            // below this ticket
            decr_level_all_tickets($ticket_no);
        } else {
            $query = update_ticket_value($parent,$value);
            //echo $query;
            $result = db_query($query);
        }
        $j++;
    }

    sem_release($semaphore);

}

function decr_level_all_tickets($parent_ticket) {
        $query=get_all_childs($parent_ticket);
        //echo $query;
        $result = db_query($query);

        while($row = mysql_fetch_array($result)) {
            if($row['level']==1) {
                $query = update_ticket_level_and_parent($row['ticket_no'], $row['level']-1, 0);
            } else {
                $query = update_ticket_level($row['ticket_no'], $row['level']-1);
            }
            //echo $query;
            $result1 = db_query($query);
            
            decr_level_all_tickets($row['ticket_no']);
        }
}

function print_all_tickets_below($parent_ticket) {
        $query=get_all_childs($parent_ticket);
        $result = db_query($query);

        while($row = mysql_fetch_array($result) ) {
            if($row['level']>=3) {
                continue;
            }
            echo '<ticket>';
            try {
                echo '<level>'.$row['level'].'</level>';
                echo '<ticket_no>'.$row['ticket_no'].'</ticket_no>';
                echo '<parent_ticket_no>'.$row['parent_ticket_no'].'</parent_ticket_no>';
                echo '<max_coupon_value>'.$row['max_coupon_value'].'</max_coupon_value>';
                echo '<value>'.$row['value'].'</value>';
            } catch (Exception $e) {
                echo '</ticket>';
                echo "<result>Error</result>";
                break;
            }
            echo '</ticket>';

            print_all_tickets_below($row['ticket_no']);
        }
}



?>
